package com.ruoyi.hr.controller.hr;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.hr.domain.Authority;
import com.ruoyi.hr.domain.salaryCalculation.SkypayGroups;
import com.ruoyi.hr.service.AuthorityService;
import com.ruoyi.hr.service.EmpSalaryCalculationService;
import com.ruoyi.hr.service.SkyMsgAlarmService;
import com.ruoyi.hr.util.BaseResult;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/salaryCalculation")
public class EmpSalaryCalculationController extends BaseController {
    @Autowired
    private EmpSalaryCalculationService empSalaryCalculationService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    SkyMsgAlarmService skyMsgAlarmService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    AuthorityService authorityService;

    private String prefix = "hr/empSalaryCalculation";

    /**
     * 跳转分页页面
     */
    @GetMapping()
    public String user() {
        return prefix + "/empSalaryCalculation";
    }

    @GetMapping("calculation")
    public String calculation(String pgid, ModelMap mmap) {
        mmap.put("pgid", pgid);
        return prefix + "/calculation";
    }

    @GetMapping("attend")
    public String attend(String pgid, ModelMap mmap) {
        mmap.put("pgid", pgid);
        return prefix + "/attend";
    }


    @GetMapping("adjust")
    public String adjust(String pgid, ModelMap mmap) {
        mmap.put("pgid", pgid);
        return prefix + "/adjust";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData(String title) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        Ztree ztree[] = {
                new Ztree((long) 101, (long) 0, "薪资接口", "薪资接口"),
                new Ztree((long) 102, (long) 101, "考勤数据", "考勤数据"),
                new Ztree((long) 103, (long) 101, "应加应扣", "应加应扣"),
                new Ztree((long) 104, (long) 0, "薪资计算", "薪资计算"),
        };
        //动态获取薪资套
        //获取登录人urid
        SysUser user = ShiroUtils.getSysUser();
        Map<String, Object> maps = iSysUserService.selectSkySecUser(user.getLoginName());
        int num = 106;
        List<SkypayGroups> skypayGroupsList = empSalaryCalculationService.findSkypayGroups(maps.get("id").toString());
        for (SkypayGroups skypayGroups : skypayGroupsList) {
            Ztree ztree1 = new Ztree((long) num, (long) 104, skypayGroups.getTitle(), skypayGroups.getId().toString());
            ztrees.add(ztree1);
            num++;
        }

        for (int i = 0; i < ztree.length; i++) {
            ztrees.add(ztree[i]);
        }

        ztrees.add(new Ztree((long) 400, (long) 0, "特殊人员薪资登记", "400"));
        ztrees.add(new Ztree((long) 401, (long) 400, "特殊人员登记", "401"));
        ztrees.add(new Ztree((long) 402, (long) 400, "特殊人员薪资登记", "402"));
        ztrees.add(new Ztree((long) 403, (long) 400, "特殊人员薪资查询", "403"));
        ztrees.add(new Ztree((long) 404, (long) 0, "拜特薪资模板", "404"));
        ztrees.add(new Ztree((long) 405, (long) 404, "拜特薪资", "405"));

        return ztrees;
    }

    /**
     * 获取薪资套人员
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map map) {
        List<Map> list = new ArrayList<Map>();
        String pgid = map.get("pgid").toString();
        String jsid = getJSID(pgid);
        map.put("jsid", jsid);
        if (jsid == null) {
            return getDataTable1(list, 0);
        } else {
            List<String> ProList = empSalaryCalculationService.findObjType(pgid);
            String sql = getSql(ProList, map);
            list = empSalaryCalculationService.findEmpSalaryInfoList(sql.toString());
            return getDataTable1(list, list.size());
        }
    }

    /**
     * 获取薪资套列表
     *
     * @return 薪资套列表集合
     */
    @PostMapping("/getSkypayGroups")
    @ResponseBody
    public List<SkypayGroups> getSkypayGroups() {
        SysUser user = ShiroUtils.getSysUser();
        Map<String, Object> maps = iSysUserService.selectSkySecUser(user.getLoginName());
        return empSalaryCalculationService.findSkypayGroups(maps.get("id").toString());
    }

    /**
     * 计算薪资套
     *
     * @return 计算薪资套
     */
    @PostMapping("/skyPayGroupSubmitpgid")
    @ResponseBody
    public void skyPayGroupSubmitpgid(String pgid) {
        String sql = "skyPayGroupSubmit" + pgid + " " + pgid + ",1,0";
        //计算
        empSalaryCalculationService.skyPayGroupSubmitpgid(sql);
        //计算后
        sql = "skyPayGroupSubmit" + " " + pgid + ",1,0";
        empSalaryCalculationService.skyPayGroupSubmit(sql);
    }

    /**
     * 获取JSID
     *
     * @return pgid
     */
    @PostMapping("/getJSID")
    @ResponseBody
    public String getJSID(String pgid) {
        String JSID = empSalaryCalculationService.getJSID(pgid);
        return JSID;
    }

    /**
     * 根据薪资套类型获取所有项目
     *
     * @param pgid 薪资套ID
     * @return
     */
    @RequestMapping("getPro")
    @ResponseBody
    public List<String> getPro(String pgid) {
        List<String> ProList = empSalaryCalculationService.findObjTypeAll(pgid);
        for (int i = 0; i < ProList.size(); i++) {
            ProList.set(i, ProList.get(i).replace("（", "("));
            ProList.set(i, ProList.get(i).replace("）", ")"));
        }
        return ProList;
    }

    /**
     * 获取考勤项目(通用)
     *
     * @return
     */
    @RequestMapping("getProKQ")
    @ResponseBody
    public List<String> getProKQ() {
        List<String> ProList = empSalaryCalculationService.findKQ();
        return ProList;
    }

    /**
     * 获取应加应扣项目
     *
     * @return
     */
    @RequestMapping("getProYJYK")
    @ResponseBody
    public List<String> getProYJYK(String pgid) {
        List<String> ProList = empSalaryCalculationService.findYJYK(pgid);
        for (int i = 0; i < ProList.size(); i++) {
            ProList.set(i, ProList.get(i).replace("（", "("));
            ProList.set(i, ProList.get(i).replace("）", ")"));
        }
        return ProList;
    }


    /**
     * 获取新的term
     */
    @RequestMapping("findNewTerm")
    @ResponseBody
    public BaseResult findNewTerm(String pgid) {
        BaseResult baseResult = empSalaryCalculationService.findNewTerm(pgid);
        return baseResult;
    }

    /**
     * 获取考勤项目信息数据
     *
     * @return
     */
    @RequestMapping("getSkyPayItemObjs")
    @ResponseBody
    public TableDataInfo getSkyPayItemObjs(@RequestParam Map map) {
        String pgid = map.get("pgid").toString();
        String jsid = getJSID(pgid);
        map.put("jsid", jsid);
        List<Map> list = new ArrayList<Map>();
        if (jsid != null) {
            List<String> ProList = empSalaryCalculationService.findKQ();
            String sql = getSql(ProList, map);
            list = empSalaryCalculationService.findEmpSalaryInfoList(sql.toString());
        }
        return getDataTable1(list, list.size());
    }

    /**
     * 获取应加应减项目信息数据
     *
     * @return
     */
    @RequestMapping("getaddreduce")
    @ResponseBody
    public TableDataInfo getaddreduce(@RequestParam Map map) {
        String pgid = map.get("pgid").toString();
        String jsid = getJSID(pgid);
        map.put("jsid", jsid);
        List<Map> list = new ArrayList<>();
        if (jsid != null) {
            List<String> ProList = empSalaryCalculationService.findYJYK(pgid);
            String sql = getSql(ProList, map);
            list = empSalaryCalculationService.findEmpSalaryInfoList(sql.toString());
        }
        return getDataTable1(list, list.size());
    }

    @RequestMapping("executeProcedure")
    @ResponseBody
    public String executeProcedure(@RequestParam Map map) {
        return empSalaryCalculationService.salaryProcess(map);
    }


    public String getSql(List<String> ProList, Map map) {
        StringBuffer forSql = new StringBuffer("");
        for (int i = 0; i < ProList.size(); i++) {
            ProList.set(i, ProList.get(i).replace("（", "("));
            ProList.set(i, ProList.get(i).replace("）", ")"));
            if (i == ProList.size() - 1) {
                forSql.append("[" + ProList.get(i) + "]");
            } else {
                forSql.append("[" + ProList.get(i) + "],");
            }
        }
        StringBuffer sql = new StringBuffer("select * from (select convert(char(7),时间,21) as '时间',badge,name,cpid,ogid,公司名称,部门名称,岗位名称,在岗状态,convert(char(10),EmpStartDate,21) as EmpStartDate,ISNULL(convert(char(10),empEndDate,21) , '') EmpEndDate,pzidName,convert(char(10),StartDate,21) as StartDate,");
        sql.append(forSql);
        sql.append(" from (SELECT * FROM xVW_SalaryInfo where JSID = ");
        sql.append(map.get("jsid"));
        sql.append(" and 时间 = (select term from skyPayGroupProcess where ID = ");
        sql.append(map.get("jsid"));
        sql.append(")) a PIVOT ( max(a.值) for a.项目 in( ");
        sql.append(forSql);
        sql.append(")) b) t where 1=1 ");
        if (map.get("badge") != null && !"".equals(map.get("badge"))) {
            sql.append(" and t.badge like N'%" + map.get("badge") + "%'");
        }
        if (map.get("name") != null && !"".equals(map.get("name"))) {
            sql.append(" and t.name like N'%" + map.get("name") + "%'");
        }


        //权限
        SysUser user = ShiroUtils.getSysUser();
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());

        int isAdmin = 0;
        if (authorityList.size() == 1) {
            if (authorityList.get(0).getIsAdmin() != null) {
                isAdmin = 1;
            }
        }

        if (isAdmin == 0) {
            if (null != authorityList) {
                sql.append("and ogid in(");
                for (Authority authority : authorityList) {
                    if (!"".equals(authority.getDepIds())) {
                        sql.append(authority.getDepIds() + ",");
                    }
                }
                sql.delete(sql.length() - 1, sql.length());
                sql.append(")");
            }
        }

        if (map.get("orderByColumn") != null && !"".equals(map.get("orderByColumn")) && !"".equals(map.get("isAsc"))) {
            sql.append(" order by " + map.get("orderByColumn") + " " + map.get("isAsc") +" ");
        }

        return sql.toString();
    }

    /**
     * 下载考勤应加应扣模板
     *
     * @param type 判断下载模板类型 kq=考勤 yjyk=应加应扣
     * @return
     * @throws Exception
     */
    @RequestMapping("/downloadTemplate")
    @ResponseBody
    public AjaxResult downloadTemplate(String type, String pgid) throws Exception {
        return empSalaryCalculationService.downloadTemplate(type, pgid);
    }

    /**
     * 导入考勤Excel
     * author : Zeo
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String pgid, String type) throws Exception {
        return empSalaryCalculationService.importData(file, updateSupport, pgid, type);
    }

    /**
     * 刷新按钮组件
     */
    @PostMapping("/refreshButton")
    @ResponseBody
    public Map<String, Object> refreshButton(String pgid) {
        Map<String, Object> map = empSalaryCalculationService.refreshButton(pgid);
        if (null == map) {
            map = new HashMap<String, Object>();
            map.put("initialized", false);
            map.put("submit", false);
            map.put("frozen", false);
            map.put("cancelFrozen", false);
            map.put("closed", false);
        }
        return map;
    }

    /**
     * 导出
     */
    @RequestMapping("/exportSalaryData")
    @ResponseBody
    public AjaxResult exportSalaryData(String pgid) throws Exception {
        Map map = new HashMap();
        List<Map> list = new ArrayList<Map>();
        map.put("pgid", pgid);
        String jsid = getJSID(pgid);
        map.put("jsid", jsid);
        List<String> ProList = empSalaryCalculationService.findObjType(pgid);
        String sql = getSql(ProList, map);
        list = empSalaryCalculationService.findEmpSalaryInfoList(sql.toString());
        return empSalaryCalculationService.exportSalaryData(pgid, list);
    }
}

